<?php

namespace app\wap\controller;

use think\Controller;
use think\Db;

/**
 * 登录
 * Class Base
 * @package app\app\controller
 */
class Wx extends Controller {

    private $appid = 'wxff4f4431a068f4ed';
    private $secret = 'a8a30483fc1dd409c06f28dc455ec63c';
    private $base = 'https://kis8.com/wx';

    //入口登录那里
    public function index() {
//        "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxff4f4431a068f4ed&redirect_uri=https://www.hangziwang.cn/2.php&response_type=code&scope=snsapi_base&state=123#wechat_redirect"
        $clickurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=https://kis8.com/wx&response_type=code&scope=snsapi_userinfo#wechat_redirect";
        header('Location:' . $clickurl);
        exit;
    }
    public function aa(){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->secret}&code={$_GET['code']}&grant_type=authorization_code";
        $output = $this->get_curl($url);
        $output_array = json_decode($output, true);
        session("open_id",$output_array['openid'],120);
        header('Location:' ."http://kis8.com/wap_index");
//        dd($output_array);
    }
    /**
     * 获取access_token
     */
    public function getAccessToken() {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
        $output = $this->get_curl($url);
        $output_array = json_decode($output, true);
        return $output_array;
    }

    /**
     * 获取openid
     */
    public function redirects() {

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->secret}&code={$_GET['code']}&grant_type=authorization_code";

        $output = $this->get_curl($url);
        $output_array = json_decode($output, true);

        $access_token = $output_array['access_token'];
        $openid = $output_array['openid'];

        $refresh_token = $output_array['refresh_token'];

        //如果scope=snsapi_base，这里的$out_array数据就只有用户openid数据，这种授权用户无感知
        //如果scope=snsapi_userinfo，这里的$out_array数据就是用户的详细信息，这种授权会弹出一个授权页面，提示用户授权
        //获取用户信息后的逻辑处理
        //第一步：判断这个openid是否已经存在
        $result = Db::name('store_member')->where(['openid' => $openid])->find();
        if ($result) {
            //更新token值
            //  $token = md5($result['id'] . time());
            //  Db::name('tokens')->where(['uid' => $result['id'], 'type' => 2])->update(['token' => $token]);
            $token = Db::name('tokens')->where(['uid' => $result['id'], 'type' => 2])->value('token');
            //判断用户是否认证成功，没有认证成功的就跳转到认证页面，认证成功了的就跳转到我的页面
            /*             * if ($result['is_auth'] == 1) {
              //没认证的
              $url = "http://ssq.90buluo.com/index.php/store/Authentication/Authentication?token=" . $token;
              } else {
              //认证成功
              $url = "http://ssq.90buluo.com/index.php/store/User/index?token=" . $token;
              } */
            $url = "http://ssq.90buluo.com/web/h5/index.html#/?token=" . $token;
            header('Location:' . $url);
            exit;
        } else {
            //获取用户信息

            $out_array = $this->get_one_user($access_token, $openid);


            //添加进数据库
            $add_info = [
                'nickname' => $out_array['nickname'],
                'head' => $out_array['headimgurl'],
                'sex' => $out_array['sex'],
                'openid' => $out_array['openid'],
                'salesman_id' => $out_array['qr_scene'],
                'create_time' => time(),
                'login_time' => time(),
            ];
            Db::name('store_member')->insert($add_info);
            $id = Db::name('store_member')->getLastInsID();
            //添加进token表
            $token = md5($result['id'] . time());
            Db::name('tokens')->insert(['uid' => $id, 'token' => $token, 'type' => 2]);
            $url = "http://ssq.90buluo.com/web/h5/index.html#/?token=" . $token;
            header('Location:' . $url);
            exit;
        }
    }
    /**
     *无感知获取用户信息
     */
    public function get_one_user($access_token, $openid) {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $output = $this->get_curl($url);
        $output_array = json_decode($output, true);
        return $output_array;
    }
    /**
     *需要用户点击允许
     */
    public function get_one_userinfo($access_token, $openid) {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
        $output = $this->get_curl($url);
        $output_array = json_decode($output, true);
        return $output_array;
    }

    function get_curl($url, $post_data = array()) {

        //初始化
        $ch = curl_init();
        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        }
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        if (!empty($post_data)) {
            curl_setopt($ch, CURLOPT_POST, 1); //设置为POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // => array('v' => $v, 'p' => $str, 'c' => $c, 's' => $encrpt), //POST数据
        }
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        curl_close($ch);

        //释放curl句柄
        //打印获得的数据
        return $output;
    }

}
